<style module>
.me {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  padding: 0 5px;
}
.title {
  font-size: 25px;
  font-weight: 300;
}
.wrapStyle {
  display: inline-block;
  width: 100%;
  height: 32px;
  line-height: 1.5;
  padding: 4px 7px;
  font-size: 14px;
  border: 1px solid #dcdee2;
  border-radius: 4px;
  color: #515a6e;
  background-color: #fff;
  background-image: none;
  position: relative;
  transition: border .2s ease-in-out,background .2s ease-in-out,box-shadow .2s ease-in-out;
}
.formStyle {

}
.dateStyle{
  width:100%;
}
.numStyle{
  width:100%;
}
</style>
<template>
  <div :class="$style.me">
    <Divider v-if="!!title" orientation="left"><span :class="$style.title" :style="titleStyle">{{title}}</span></Divider>
    <Form v-if="show" ref="_frm" :model="cloneData"  :rules="ruleValidate"  :disabled="form.disabled" :label-width="form.labelWidth" :style="myFormStyle">
      <Row v-for="(colList,index) in fieldsList" :key="index">
        <Col v-for="(field,k) in colList" :key="k" :span="span" :style="{padding:'0 5px'}">
          <FormItem :label="field.label" :prop="field.dataIndex" :style="{marginBottom:form.interval,width:itemWidth}">
            <Input v-if="['input','String','text','Input','string','Text'].includes(field.editor)"  v-model="cloneData[field.dataIndex]" :readonly="field.readonly" :disabled="field.disabled"></Input>
            <Select v-else-if="['select'].includes(field.editor)"  :disabled="field.disabled" v-model="cloneData[field.dataIndex]">
              <Option v-for="(op,i) in field.options" :key="i" :value="op.value">{{ op.label }}</Option>
            </Select>
            <Select v-else-if="['multiselect','array','Array'].includes(field.editor)"   v-model="cloneData[field.dataIndex]" multiple transfer>
              <Option v-for="(op,i) in field.options" :key="i" :value="op.value">{{ op.label }}</Option>
            </Select>
            <RadioGroup v-else-if="['radio','Radio'].includes(field.editor)&&!form.itemAlign"  v-model="cloneData[field.dataIndex]">
              <Radio v-for="(op,i) in field.options" :key="i" :label="op.label">{{ op.label }}</Radio>
            </RadioGroup>
            <CheckboxGroup v-else-if="['multicheck','multicheckbox','checkboxGroup','CheckboxGroup'].includes(field.editor)&&!form.itemAlign"  v-model="cloneData[field.dataIndex]">
              <Checkbox v-for="(op,i) in field.options" :key="i" :label="op.label">{{ op.label }}</Checkbox>
            </CheckboxGroup>
            <Checkbox  v-else-if="['check','Boolean','Check','boolean'].includes(field.editor)&&!form.itemAlign"  :disabled="field.disabled" v-model="cloneData[field.dataIndex]"></Checkbox>
            <div :class="$style.wrapStyle" v-else-if="['radio','Radio'].includes(field.editor)&&form.itemAlign">
              <RadioGroup v-model="cloneData[field.dataIndex]">
                <Radio v-for="(op,i) in field.options" :key="i" :label="op.label">{{ op.label }}</Radio>
              </RadioGroup>
            </div>
            <div :class="$style.wrapStyle"  v-else-if="['multicheck','multicheckbox','checkboxGroup','CheckboxGroup'].includes(field.editor)&&form.itemAlign">
              <CheckboxGroup v-model="cloneData[field.dataIndex]">
                <Checkbox v-for="(op,i) in field.options" :key="i" :label="op.label">{{ op.label }}</Checkbox>
              </CheckboxGroup>
            </div>
            <div :class="$style.wrapStyle"  v-else-if="['check','Boolean','Check','boolean'].includes(field.editor)&&form.itemAlign">
              <Checkbox v-model="cloneData[field.dataIndex]"></Checkbox>
            </div>
            <DatePicker v-else-if="['date','Date'].includes(field.editor)" type="date" :style="form.itemAlign?{width:'100%'}:''" show-week-numbers  transfer format="yyyy-MM-dd" v-model="cloneData[field.dataIndex]"></DatePicker>
            <TimePicker v-else-if="['time','Time'].includes(field.editor)" type="time" :style="form.itemAlign?{width:'100%'}:''" show-week-numbers  transfer format="HH:mm:ss" v-model="cloneData[field.dataIndex]"></TimePicker>
            <DatePicker v-else-if="['datetime','Datetime','DateTime'].includes(field.editor)" type="datetime" :style="form.itemAlign?{width:'100%'}:''" show-week-numbers  transfer format="yyyy-MM-dd HH:mm:ss" v-model="cloneData[field.dataIndex]"></DatePicker>
            <DatePicker v-else-if="['datetimerange'].includes(field.editor)" type="datetimerange" :style="form.itemAlign?{width:'100%'}:''" show-week-numbers  transfer format="yyyy-MM-dd HH:mm:ss" v-model="cloneData[field.dataIndex]"></DatePicker>
            <DatePicker v-else-if="['daterange'].includes(field.editor)" type="daterange" :style="form.itemAlign?{width:'100%'}:''" show-week-numbers  transfer format="yyyy-MM-dd" v-model="cloneData[field.dataIndex]"></DatePicker>
            <ColorPicker v-else-if="['color'].includes(field.editor)" v-model="cloneData[field.dataIndex]" :transfer="true"/>
            <i-switch v-else-if="['switch'].includes(field.editor)&&!form.itemAlign" v-model="cloneData[field.dataIndex]"></i-switch>
            <div :class="$style.wrapStyle"  v-else-if="['switch'].includes(field.editor)&&form.itemAlign">
              <i-switch v-model="cloneData[field.dataIndex]"></i-switch>
            </div>
            <Slider v-else-if="['slider','numberRange'].includes(field.editor)&&!form.itemAlign" v-model="cloneData[field.dataIndex]" range></Slider>
            <div :class="$style.wrapStyle"  v-else-if="['slider','numberRange'].includes(field.editor)&&form.itemAlign">
              <Slider v-model="cloneData[field.dataIndex]" range></Slider>
            </div>
            <InputNumber v-else-if="['int','number'].includes(field.editor)" :readonly="field.readonly" v-model="cloneData[field.dataIndex]"  :style="form.itemAlign?{width:'100%'}:''" :max="field.max" :min="field.min" :step="field.step"></InputNumber>
            <InputNumber v-else-if="['percent'].includes(field.editor)" v-model="cloneData[field.dataIndex]"  :style="form.itemAlign?{width:'100%'}:''"
                         :max="field.max"
                         :min="field.min"
                         :step="field.step"
                         :formatter="value => `${value*100}%`"
                         :parser="value => value.replace('%', '')/100"
            ></InputNumber>
            <Input v-else-if="['textarea','description'].includes(field.editor)" v-model="cloneData[field.dataIndex]" type="textarea" :autosize="{minRows: field.minRows,maxRows: field.maxRows}"></Input>
            <City v-else-if="['city','City'].includes(field.editor)" v-model="cloneData[field.dataIndex]" show-suffix :transfer="true" />
            <span v-else>{{cloneData[field.dataIndex]}}</span>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <Row v-if="showBtn&&newForm" justify="end">
      <Poptip confirm transfer
              :title="$i18n.locale==='en'?'Confirm Prompt':'确认提示'"
              :style="{alignSelf:'flex-start',margin:'5px'}"
              @on-ok="newSave">
        <Button type="primary" size="small">{{$i18n.locale==='en'?'Submit':'提交'}}</Button>
      </Poptip>
      <Button style="margin:5px;" size="small" @click="cancel">{{$i18n.locale==='en'?'Cancel':'取消'}}</Button>
    </Row>
    <Row v-else-if="showBtn" justify="end">
      <Poptip confirm transfer
              :title="$i18n.locale==='en'?'Confirm Prompt':'确认提示'"
              :style="{alignSelf:'flex-start',margin:'5px'}"
              @on-ok="submit">
        <Button type="primary" size="small">{{$i18n.locale==='en'?'Submit':'提交'}}</Button>
      </Poptip>
      <Button v-if="newOp" type="info" size="small" style="margin:5px;" @click="newItem">{{$i18n.locale==='en'?'Add':'新增'}}</Button>
      <Poptip v-if="newOp" confirm transfer
              :title="$i18n.locale==='en'?'Confirm Prompt':'确认提示'"
              :style="{alignSelf:'flex-start',margin:'5px'}"
              @on-ok="deleteItem">
        <Button type="warning" size="small">{{$i18n.locale==='en'?'Delete':'删除'}}</Button>
      </Poptip>
    </Row>
  </div>
</template>

<script>
export default {
  model:{
    prop:'data',
    event:'submit'
  },
  data() {
    return {
      ruleValidate:{},
      cloneData: {},
      newForm:false,
      tpl:{},
      show:true,
    }
  },
  props: {
    showBtn:{
      default:()=>true
    },
    newOp:{default:()=>false},
    data:{default:()=>{
      return {}
    }},
    title:{
      default:()=>{
        return null;
      }
    },
    titleStyle:{
      default:()=>{
        return {};
      }
    },
    formStyle:{
      default:()=>{
        return {};
      }
    },
    form:{
      default:()=> {
        return {
          labelWidth:160,
          interval:'24px',
          itemWidth:null,
          itemAlign:true,
          col:2,
          disabled:false
        }
      }
    },
    fields:{
      default:()=>{
        return [];
      }
    },
  },
  components: {},
  computed: {
    myFormStyle(){
      return Object.assign({overflow:'auto',padding:'5px',border:'0px solid #dcdee2'},this.formStyle)
    },
    col(){
      return this.lodash.isInteger(this.form.col)&&this.form.col>0?this.form.col:1;
    },
    span(){
      return parseInt(24/this.col);
    },
    itemWidth(){
      return !!this.form.itemWidth?this.form.itemWidth:'auto';
    },
    fieldsList(){
      return this.lodash.chunk(this.fields,this.col);
    }
  },
  mounted() {
    this.cloneData=this.lodash.cloneDeep(this.data);
    this.getRuleValidate();
  },
  watch:{
    form:function(form){
      this.getRuleValidate();
    },
    data:function(newData){
      this.cloneData=this.lodash.cloneDeep(newData);
    }
  },
  methods: {
    refresh() {
      this.$forceUpdate();
    },
    getRuleValidate(){
      let rule={};
      let tpl={};
      this.fields.map(field=>{
        rule[field.dataIndex]=[
          { required:field.required, type:field.validate, message:this.$i18n.locale==='en'?'wrong value':'错误的值', trigger: 'change' },
        ];
        tpl[field.dataIndex]=field.defaultValue;
      });
      this.ruleValidate=rule;
      this.tpl=tpl;
    },
    submit(){
      this.$refs._frm.validate((valid) => {
        if (valid) {
          this.$emit('submit',this.cloneData);
        } else {
          this.$Message.error(this.$i18n.locale==='en'?'validate does not pass!':'验证未通过！');
        }
      })
    },
    reset (name) {
      this.$refs._frm.resetFields();
    },
    newItem(){
      this.cloneData=this.lodash.cloneDeep(this.tpl);
      this.newForm=true;
    },
    newSave () {
      this.$refs._frm.validate((valid) => {
        if (valid) {
          this.newForm=false;
          this.$emit('formAddItem',this.cloneData);
        } else {
          this.$Message.error(this.$i18n.locale==='en'?'validate does not pass!':'验证未通过！');
        }
      })
    },
    deleteItem(){
      this.$emit('formDeleteItem',this.cloneData);
    },
    cancel(){
      this.newForm=false;
      this.cloneData=this.lodash.cloneDeep(this.data);
    }
  }
}
</script>
<!--
string: Must be of type string. This is the default type.
number: Must be of type number.
boolean: Must be of type boolean.
method: Must be of type function.
regexp: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.
integer: Must be of type number and an integer.
float: Must be of type number and a floating point number.
array: Must be an array as determined by Array.isArray.
object: Must be of type object and not Array.isArray.
enum: Value must exist in the enum.
date: Value must be valid as determined by Date
url: Must be of type url.
hex: Must be of type hex.
email: Must be of type email.
any: Can be any type.-->
